package com.yex.utils;

import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class MathUtil {

	public final static int RESULT_SCALE = 8;

	private final static int CAL_SCALE = 12;
	//负一
	private final static BigDecimal NEG_ONE = new BigDecimal("-1");
	
	public final static BigDecimal MIN_VAL = new BigDecimal("0.00000001");
	public final static BigDecimal NEG_MIN_VAL = new BigDecimal("-0.00000001");
	public static final BigDecimal TWO = new BigDecimal("2");
	public static final BigDecimal ONEHUNDRED = new BigDecimal("100");
	public static final BigDecimal TEN = new BigDecimal("10");
	public static final BigDecimal ZERO = new BigDecimal("0.00000000");
	
	
	public static BigDecimal add(BigDecimal one,BigDecimal two) {
		if(one==null) {
			one = BigDecimal.ZERO;
		}
		if(two==null) {
			two = BigDecimal.ZERO;
		}
		BigDecimal result = one.add(two);
		result = result.setScale(CAL_SCALE, RoundingMode.DOWN);
		return result;
	}
	
	public static BigDecimal neg(BigDecimal one) {
		return mul(one,NEG_ONE);
	}
	
	public static String getBigDecimalString(BigDecimal one) {
		return getBigDecimalString(one, RESULT_SCALE);
	}
	
	public static String getBigDecimalString(BigDecimal one,int scale) {
		if(one == null) {
			return "";
		}
		one = one.setScale(scale, RoundingMode.DOWN);
		return one.toPlainString();
	}

	/**
	 * 转换
	 * @param one 转换数字
	 * @param scale 小数位
	 * @param roundingMode 模式
     * @return
     */
	public static String getBigDecimalString(BigDecimal one,int scale,RoundingMode roundingMode) {
		if(one == null) {
			return "";
		}
		one = one.setScale(scale, roundingMode);
		return one.toPlainString();
	}
	
	public static BigDecimal getBigDecimal(BigDecimal one,int scale) {
		if(one==null) {
			return BigDecimal.ZERO;
		}
		one = one.setScale(scale, RoundingMode.DOWN);
		return one;
	}


	
	public static BigDecimal getBigDecimal(BigDecimal one) {
		return getBigDecimal(one, RESULT_SCALE);
	}
	
	public static BigDecimal sub(BigDecimal one,BigDecimal two) {
		if(one==null) {
			one = BigDecimal.ZERO;
		}
		if(two==null) {
			two = BigDecimal.ZERO;
		}
		BigDecimal result = one.subtract(two);
		result = result.setScale(CAL_SCALE, RoundingMode.DOWN);
		return result;
	}
	
	
	public static BigDecimal mul(BigDecimal one,BigDecimal two) {
		BigDecimal result = one.multiply(two);
		result = result.setScale(CAL_SCALE, RoundingMode.DOWN);
		return result;
	}


	public static BigDecimal div(BigDecimal one,BigDecimal two) {
		BigDecimal result = one.divide(two, CAL_SCALE, RoundingMode.DOWN);
		return result;
	}

	public static BigDecimal getBigDecimal(Object obj) {
		if(obj==null) {
			return BigDecimal.ZERO;
		}
		if(obj instanceof BigDecimal) {
			return (BigDecimal)obj;
		}
		String val = obj.toString();
		if(StringUtils.isNumeric(val)) {
			return new BigDecimal(val);
		}else {
			return BigDecimal.ZERO;
		}
		
		
	}







}
